<template>
  <section class="box comments">
    <hr />
    <h3 class="title is-5">Comments</h3>
    <comment-form :postId="postId" v-if="token" @loadComments="fetchComments"></comment-form>
    <comment-item v-for="comment in comments" :key="comment.id" :comment="comment"></comment-item>
  </section>
</template>

<script>
import { mapGetters } from 'vuex'
import { getComments } from '../../../api/comment'
import CommentItem from './CommentItem.vue'
import CommentForm from "./CommentForm.vue"

export default {
  name: 'Comment',
  components: {
    CommentItem,
    CommentForm
  },
  data() {
    return {
      comments: []
    }
  },
  props: ['postId'],
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  mounted() {
     this.fetchComments();
  },
  methods: {
      // 初始化
      fetchComments(){
          console.log(this.postId);
          getComments(this.postId).then(res=>{
              const result = res.data;
              if(result.code == 0){
                  this.comments = result.data;
              }
          })
      },
  },
  //监听路由发生的变化对当前同一组件的留言进行及时切换更新
  watch:{
    '$route'(to){
      this.postId = to.params.id;
      this.fetchComments();
    }
  }
}
</script>